"""Word文档生成模块 - 使用python-docx生成docx文件"""

from datetime import datetime
from typing import List, Optional
from docx import Document
from docx.shared import Pt, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn

from .models import Table


class WordWriter:
    """Word文档生成器"""
    
    def __init__(self, dialect: str = 'mysql'):
        """
        初始化文档生成器
        
        Args:
            dialect: 数据库类型
        """
        self.dialect = dialect
        self.doc = Document()
        self._setup_document()
    
    def _setup_document(self):
        """设置文档基本样式"""
        # 设置默认字体为宋体
        style = self.doc.styles['Normal']
        font = style.font
        font.name = '宋体'
        font.size = Pt(10.5)
        # 设置中文字体
        try:
            font._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
        except:
            # 如果设置失败，尝试其他方式
            pass
        
        # 设置标题样式的中文字体
        for style_name in ['Heading 1', 'Heading 2', 'Heading 3']:
            if style_name in self.doc.styles:
                heading_style = self.doc.styles[style_name]
                heading_font = heading_style.font
                heading_font.name = '宋体'
                try:
                    heading_font._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
                except:
                    pass
    
    def write_tables(self, tables: List[Table], output_path: str):
        """
        将表结构写入Word文档
        
        Args:
            tables: 表结构列表
            output_path: 输出文件路径
        """
        # 添加封面页（可选）
        self._add_cover_page()
        
        # 添加正文内容
        for table in tables:
            self._add_table_section(table)
        
        # 保存文档
        self.doc.save(output_path)
    
    def _add_cover_page(self):
        """添加封面页"""
        # 标题
        title = self.doc.add_heading('数据库表结构说明文档', 0)
        title.alignment = WD_ALIGN_PARAGRAPH.CENTER
        
        # 添加空行
        self.doc.add_paragraph()
        
        # 生成时间
        time_para = self.doc.add_paragraph()
        time_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
        time_run = time_para.add_run(f'生成时间：{datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")}')
        time_run.font.size = Pt(12)
        
        # 数据库类型
        dialect_para = self.doc.add_paragraph()
        dialect_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
        dialect_map = {
            'mysql': 'MySQL',
            'postgres': 'PostgreSQL',
            'kingbase': '人大金仓（KingbaseES）'
        }
        dialect_name = dialect_map.get(self.dialect, self.dialect.upper())
        dialect_run = dialect_para.add_run(f'数据库类型：{dialect_name}')
        dialect_run.font.size = Pt(12)
        
        # 添加分页符
        self.doc.add_page_break()
    
    def _add_table_section(self, table: Table):
        """添加表结构章节"""
        # 表名作为一级标题
        heading = self.doc.add_heading(f'表名：{table.name}', level=1)
        
        # 如果有表注释，添加说明
        if table.comment:
            comment_para = self.doc.add_paragraph(f'表说明：{table.comment}')
            comment_para.style = 'Normal'
        
        # 添加空行
        self.doc.add_paragraph()
        
        # 创建字段说明表格
        self._add_fields_table(table.columns)
        
        # 添加空行
        self.doc.add_paragraph()
    
    def _add_fields_table(self, columns: List):
        """添加字段说明表格"""
        # 创建表格：行数=列数+1（表头），列数=6
        table = self.doc.add_table(rows=1, cols=6)
        table.style = 'Table Grid'
        
        # 设置表头
        header_cells = table.rows[0].cells
        headers = ['字段名', '类型', '长度', '允许空', '默认值', '备注']
        for i, header in enumerate(headers):
            cell = header_cells[i]
            cell.text = header
            # 表头居中对齐
            cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
            # 设置表头字体加粗和中文支持
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True
                    run.font.name = '宋体'
                    try:
                        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
                    except:
                        pass
        
        # 添加数据行
        for column in columns:
            row_cells = table.add_row().cells
            
            # 字段名
            row_cells[0].text = column.name
            
            # 类型
            row_cells[1].text = column.type
            
            # 长度
            row_cells[2].text = column.length if column.length else '-'
            
            # 允许空
            row_cells[3].text = '否' if not column.nullable else '是'
            
            # 默认值
            row_cells[4].text = column.default if column.default else '-'
            
            # 备注
            row_cells[5].text = column.comment if column.comment else '-'
            
            # 数据行左对齐并设置中文字体
            for cell in row_cells:
                cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.LEFT
                # 确保中文字体设置
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.name = '宋体'
                        try:
                            run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
                        except:
                            pass
        
        # 设置表格列宽（自动适应）
        # 设置相对列宽
        column_widths = [1.2, 1.0, 0.8, 0.8, 1.2, 2.0]
        total_width = sum(column_widths)
        for i, width_ratio in enumerate(column_widths):
            for cell in table.columns[i].cells:
                cell.width = Inches(6.5 * width_ratio / total_width)

